package com.grgbanking.it.system.service.impl;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.grgbanking.it.common.entity.PageQuery;
import com.grgbanking.it.common.json.JSONHelper;
import com.grgbanking.it.common.util.HibernateUtil;
import com.grgbanking.it.common.util.JCrypt;
import com.grgbanking.it.common.util.poi.POIShellContructor;
import com.grgbanking.it.system.component.WXOrganizationCreator;
import com.grgbanking.it.system.dao.IDepartmentDao;
import com.grgbanking.it.system.dao.IMUserRoleDao;
import com.grgbanking.it.system.dao.IResourceDao;
import com.grgbanking.it.system.dao.IRoleDao;
import com.grgbanking.it.system.dao.IUserDao;
import com.grgbanking.it.system.entity.Department;
import com.grgbanking.it.system.entity.MUserRole;
import com.grgbanking.it.system.entity.Resource;
import com.grgbanking.it.system.entity.Role;
import com.grgbanking.it.system.entity.User;
import com.grgbanking.it.system.entity.WXDepartment;
import com.grgbanking.it.system.entity.WXUser;
import com.grgbanking.it.system.service.IUserService;

/**
 * 部门管理
 * 
 * UserService
 * 
 * @author 潘广伟
 * @Email p_3er@qq.com
 * @Date 2014-12-15 下午2:57:07
 * 
 * @version 1.0.0
 *
 */
@Service
public class UserService implements IUserService {
	@Autowired
	private IUserDao<User, Integer> userDao;
	@Autowired
	private IDepartmentDao<Department, Integer> departmentDao;
	@Autowired
	private IMUserRoleDao<MUserRole, Integer> userRoleDao;
	@Autowired
	private IResourceDao<Resource, Integer> resourceDao;
	@Autowired
	private IRoleDao<Role, Integer> roleDao;
	@Autowired
	private WXOrganizationCreator organizationCreator;

	/**
	 * 用户登录
	 * @param user
	 * @return
	 * @throws Exception 
	 */
	@Override
	public User login(User user) throws Exception {
		User loginUser = userDao.getUserByUserId(user.getUserId());
		
		if(loginUser != null && JCrypt.crypt(user.getPassword(), loginUser.getPassword()).equals(loginUser.getPassword())){
			//用户角色信息
			List<Role> roles = roleDao.findByUser(loginUser.getUserId());
			loginUser.setRoles(roles);
			
			//增加用户资源信息
			List<Resource> resources = resourceDao.findByUser(loginUser.getUserId());
			loginUser.setResources(resources);
			
			return loginUser;
		}
		return null;
	}
	
	/**
	 * 获取用户数据
	 * findUsersToJson
	 * 
	 * @param query
	 * @param name
	 * @param departmentId
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public String findUsersToJson(PageQuery query,String name,String departmentId) throws Exception {
		StringBuffer sql = new StringBuffer("select u.user_id userId,u.USER_NAME username,u.MOBIL_NO phone,u.EMAIL email,d.DEPT_ID deptId,d.DEPT_NAME departmentName,d.LONG_DEPTNAME departmentLongName from user u left join department d on d.DEPT_ID=u.DEPT_ID\n");
		
		if(StringUtils.isNotEmpty(name)){
			sql.append("where u.user_id like '%").append(name).append("%' or u.USER_NAME like '%").append(name).append("%'");
		}else if(StringUtils.isNotEmpty(departmentId)){
			sql.append("where u.DEPT_ID=").append(departmentId);
		}
	
		List<?> list = userDao.pageBySQL(sql.toString(),query.getStart(), query.getLimit());

		return JSONHelper.convertToGrid(userDao.getTotalBySQL(sql.toString()), list);
	}
	
	/**
	 * 获取所有的工程师
	 * findUsersOfIT
	 * 
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public List<User> findEngineers() throws Exception {
		List<String> ids = userRoleDao.getEnginnerUsernams();
		StringBuffer hql = new StringBuffer("from User t");
    	hql.append(" where 1=1 ").append(HibernateUtil.convertToIN(ids.toArray(new String[ids.size()]), "t.userId"));
    	System.out.println(hql);
		return userDao.findByHql(hql.toString());
	}
	
	/**
	 * 根据用户名查找用户
	 * findByUsername
	 * 
	 * @param username
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public User getUserByUsername(String username) throws Exception {
		User user = userDao.getUserByUserId(username);
		if(user != null){
			List<Role> roles = roleDao.findByUser(username);
			user.setRoles(roles);
			
			//增加用户资源信息
			List<Resource> resources = resourceDao.findByUser(username);
			user.setResources(resources);
			
			Department department = departmentDao.findById(user.getDeptId());
			user.setDepartment(department);
		}
		
		return user;
	}

	/**
	 * 为用户分配角色
	 * updateDistributeRoles
	 * 
	 * @param userId
	 * @param roleIds
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public void updateDistributeRoles(String userId, String roleIds)
			throws Exception {
		StringBuffer hql = new StringBuffer("delete MUserRole t where t.username='");
		hql.append(userId).append("'");
		userRoleDao.executeHQL(hql.toString());
		if(StringUtils.isNotEmpty(roleIds)){
			
			List<MUserRole> all = new ArrayList<MUserRole>();
			String[] ids = roleIds.split(",");
			for (int i = 0; i < ids.length; i++) {
				MUserRole userRole = new MUserRole();
				userRole.setRoleId(Integer.valueOf(ids[i]));
				userRole.setUsername(userId);
	            all.add(userRole);
			}
			
			userRoleDao.save(all);
		}
	}
	
	/**
	 * 根据微信传过来的Code获取用户
	 * getUserByCode
	 * 
	 * @param code
	 * @param agentId
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public User getUserByCode(String code,Integer agentId) throws Exception {
		String userId = organizationCreator.getUserId(code,agentId);
		if(userId == null){
			return null;
		}
		User user = userDao.getUserByUserId(userId);
		if(user != null){
			//用户角色信息
			List<Role> roles = roleDao.findByUser(user.getUserId());
			user.setRoles(roles);
			
			//增加用户资源信息
			List<Resource> resources = resourceDao.findByUser(user.getUserId());
			user.setResources(resources);
		}
		
		return user;
	}
	/**
	 * 导出所有微信用户
	 * exportUserFromWX
	 * 
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public HSSFWorkbook exportUserFromWX() throws Exception {
		List<WXDepartment> departments = organizationCreator.getAllWXDepartment();
		
		
		
		
		// 1.创建一个 workbook 
        HSSFWorkbook workbook = new HSSFWorkbook();
 
        // 2.创建一个 worksheet 
        String[] headers = { "姓名", "账号", "部门", "电话号码", "email","状态" };
        
        for(WXDepartment department : departments){
        	if(department.getParentid().equals("1")){
        		
        		POIShellContructor contructor = new POIShellContructor(workbook.createSheet(department.getName()));
        		// 设置表格默认列宽度为15个字节
        		contructor.setDefaultColumnWidth(10);
        		
        		contructor.setHeader(0, headers);
        		
        		List<WXUser> users = organizationCreator.getUsersByDepartmentId(department.getId());
        		int rowIndex = 1;
        		WXDepartment userDepartment = null;
        		for(WXUser user : users){
        			int departmentId = user.getDepartment()[0];
        			if(userDepartment == null || userDepartment.getId() != departmentId){
        				userDepartment = this.getWXDepartment(departments, departmentId);
        			}
        			HSSFRow row = contructor.createRow(rowIndex);
        			contructor.setCellText(row, 0, user.getName());
        			contructor.setCellText(row, 1, user.getUserid());
        			contructor.setCellText(row, 2, userDepartment.getName());
        			contructor.setCellText(row, 3, user.getMobile());
        			contructor.setCellText(row, 4, user.getEmail());
        			contructor.setCellText(row, 5, user.getStatus().toString());
        			rowIndex++;
        		}
        	}
        }
		
		return workbook;
	}
	
	public WXDepartment getWXDepartment(List<WXDepartment> departments,int departmentId){
		for(WXDepartment department : departments){
			if(department.getId() == departmentId){
				return department;
			}
		}
		
		return null;
	}
}